using System.Collections.Generic;
using FireStarter.CodeGeneration.Generator;

namespace FireStarter.CodeGeneration.Parser
{
    public class StatementParser : ParserBase
    {
        public static List<IActionParser> GetDefaultActionParsers()
        {
            return new List<IActionParser>
                 {
                     new ValueExpressionParser(),
                     new ForEachExpressionParser(),
                     new IfExpressionParser(),
                     new CommentExpressionParser()
                 };   
        }

        public TemplateExpression Parse(ref string templateText)
        {
            return Parse(ref templateText, GetDefaultActionParsers());
        }

        public override TemplateExpression Parse(ref string templateText, List<IActionParser> actionParsers)
        {
            if (string.IsNullOrEmpty(templateText)) return null;
            int expressionPos = templateText.IndexOf(START_TAG);
            if (expressionPos == 0)
            {
                ExpressionParser expressionParser = new ExpressionParser();
                TemplateExpression templateExpression = expressionParser.Parse(ref templateText, actionParsers);
                templateExpression.Next = Parse(ref templateText, actionParsers);
                return templateExpression;
            }
            LiteralExpression literalExpression;
            if (expressionPos < 0)
            {
                literalExpression = new LiteralExpression(templateText);
                templateText = "";
            }
            else
            {
                literalExpression = new LiteralExpression(templateText.Substring(0, expressionPos));
                string substring = templateText.Substring(expressionPos, templateText.Length - expressionPos);
                literalExpression.Next = Parse(ref substring, actionParsers);
                templateText = substring;
            }
            return literalExpression;
        }
    }
}